import pinia from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
import { usePermissionStore } from '@/stores/modules/permission.ts'
import { useSettingStore } from '@/stores/modules/setting.ts'
import { useAppStore } from '@/stores/modules/app.ts'
import { fnCurrentRouteIsPageRoute, getQueryString } from '@/utils/dynamicRoutes'
// 引入进度条插件
import NProgress from 'nprogress'
// 引入对应css样式
import 'nprogress/nprogress.css'
import { productRoutes } from './productRoutes'
import type { RouteRecordRaw, RouteLocation } from 'vue-router'

// let permissionStore = usePermissionStore(pinia)
// let settingStore = useSettingStore(pinia)
// let appStore = useAppStore(pinia)

export const pageRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/pages/login/index.vue')
  },
  {
    path: '/404',
    component: () => import('@/views/pages/404/index.vue'),
    name: '404',
    meta: {
      title: '404未找到'
    },
    beforeEnter(to, from, next) {
      console.log(to.redirectedFrom)
      // 拦截处理特殊业务场景
      // 如果, 重定向路由包含__双下划线, 为临时添加路由
      let path: string = to.redirectedFrom
      if (/__.*/.test(path)) {
        return next(path.replace(/__.*/, ''))
      }
      next()
    }
  },
  {
    path: '/screen',
    name: 'screen',
    component: () => import('@/views/pages/screen/index.vue')
  }
]
export const moduleRoutes = {
  path: '/',
  name: 'layout',
  component: () => import('@/views/layout/index.vue'),
  redirect: { name: 'home' },
  children: [
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/modules/home/index.vue')
    },
    ...productRoutes
  ]
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: pageRoutes.concat(moduleRoutes),
  scrollBehavior() {
    return {
      left: 0,
      top: 0
    }
  }
})
NProgress.configure({
  easing: 'ease',
  speed: 500,
  showSpinner: false,
  trickleSpeed: 200,
  minimum: 0.3
})
// 前置首位 访问权限控制
/**
 * to:去哪里
 * from:从哪来
 * next:路由的放行函数
 */
router.beforeEach(async (to, from, next) => {
  let permissionStore = usePermissionStore(pinia)
  let settingStore = useSettingStore(pinia)
  // 开启页面进度条
  NProgress.start()
  // if (!settingStore.theme) {
  //   await settingStore.getSystemConfig()
  //   await settingStore.getPolicy()
  // }
  const loginType = localStorage.getItem('loginType')
  // 如果是页面路由【不需要token，就可以直接进入】  或者 已经添加了动态路由
  if (
    fnCurrentRouteIsPageRoute(to, pageRoutes) ||
    window.SITE_CONFIG['dynamicMenuRoutesHasAdded']
  ) {
    next()
  } else {
    //如果没有token
    if (!permissionStore.token) {
      next({ name: 'login' })
    } else {
      //如果有token
      try {
        await permissionStore.getMenuList()
        if (to.path === '/') {
          next({
            name: window.SITE_CONFIG['dynamicHomeRoute'].name,
            replace: true
          })
        } else {
          next({
            ...to,
            replace: true
          })
        }
      } catch (error) {
        next({ name: 'login' })
      }
    }
  }
})

// 后置守卫
router.afterEach((to) => {
  // 设置页面标题
  if (typeof to.meta?.title === 'string') {
    document.title = to.meta?.title
  }
  NProgress.done()
})

export default router
